// 云函数入口文件
const cloud = require('wx-server-sdk')
const superagent = require('superagent')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.getNew) {
    //获取上课任务
    let data_skrw = await superagent
      .get(`http://8.129.187.205:3000/wyu/jwxc/skrw`)
      .then()
    let objData = JSON.parse(data_skrw.text).data
    let finalData = {}
    for (const key in objData) {
      finalData[key] = []
    }

    for (const key in objData) {
      await objData[key].forEach(item => { //数据清洗
        finalData[key].push({
          id: item.kcrwdm, //开课编号
          name: item.kcmc, //课程名称
          classmate: item.jxbmc, //教学班名称
          mateNum: item.jxbrs, //上课人数
          teacher: item.teaxm, //授课教师
          allTime: item.jhxs, //计划学时
          credit: item.xf, //学分
          studyMode: item.xdfsmc, //修读方式 
          classCategory: item.kcdlmc, //课程大类 
        })
      })
    }

    for (const key in finalData) {
      try { //存入数据库
        await db.collection('user').where({
          id: wxContext.OPENID
        }).update({
          data: {
            skrw: {
              [key]: finalData[key]
            }
          },
        })
      } catch (e) {
        return e
      }

    }

    return "ok"
  } else {
    let data = await db.collection('user').where({
      id: wxContext.OPENID
    }).get()
    return data.data[0].skrw
  }

}